﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MShop.Core.Domain;
using MShop.Core.Service;
using System.Web.Mvc;

namespace MShop.Core.DataAccess
{  
    public class ItemCatDao : CommonDao<ItemCat>, IItemCatDao
    {

        private readonly IRecursionSort<ItemCat> _RecursionService;
           private readonly IObjectContextProvider _Provider;
        public ItemCatDao(IObjectContextProvider provider,IRecursionSort<ItemCat> recursionservicce)
            :base(provider)
        {
            _RecursionService = recursionservicce;
            _Provider = provider;
        }

 

        public IEnumerable<ItemCat> Build()
        {
            IList<ItemCat> list = new List<ItemCat>();
            int rowIndex = 1;
            var enums = this.Find(x => x.ParentId == null);
            _RecursionService.Recursion(GetAll(), ref list, ref rowIndex, null);
            return list ;
        }


        public override void Delete(ItemCat entity)
        {
            HashSet<ItemCat> hashset = new HashSet<ItemCat>();
            RecursiveItemCats(entity, ref hashset);
             

            foreach (var item in hashset)
            {
                var obj = item.ItemCatProp;
                base.Delete(obj);
                base.Delete(item);
            } 

            base.Delete(entity.ItemCatProp);           
            base.Delete(entity);
        }


        private void RecursiveItemCats(ItemCat itemcat, ref HashSet<ItemCat> hashset)
        {
            hashset.Add(itemcat);
            foreach (var item in itemcat.ItemCat1)
            {
                RecursiveItemCats(item, ref hashset);
            }
        }  
 


        public IList<System.Web.Mvc.SelectListItem> BuildSelectList(object selectedValue=null,bool includeRoot = false)
        {
            IList<SelectListItem> list = new List<SelectListItem>();

            foreach (var item in Build())
            {
                SelectListItem sitem = new SelectListItem();
                sitem.Value = item.Id.ToString();

                string line = "├";
                for (int i = 0; i < item.Depth; i++)
                {
                    line += "—";
                }
                sitem.Text = string.Concat(line, item.Name);
                if (selectedValue != null)
                {
                    if (selectedValue.ToString() == sitem.Value)
                        sitem.Selected = true;
                }
                list.Add(sitem);
            }
            if (includeRoot)
            {
                list.Insert(0, new SelectListItem() { Text = "根节点", Value = "" });
            }
            return list;
        }

      
    }
}